﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Resources;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Converter;
using csla4Skeleton.UI.SL.Resources.Utility;

using csla4Skeleton.UI.SL.NghiepVu.THUE.THUE_BangKeBanRa;
using csla4Skeleton.UI.SL.TongHop.TH_SoChiTiet;
using Accounting.Library;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
using System.ComponentModel;
using Utility;
using Accounting.Library.Utility;

namespace csla4Skeleton.UI.SL.NghiepVu.THUE.THUE_BangKeBanRa
{
    public partial class THUE_BangKeBanRa_ChildWindow : ChildWindow, Csla.Xaml.ISupportNavigation
    {

        #region ISupportNavigation Members
        List<Control> controls = new List<Control>();
        public bool CreateBookmarkAfterLoadCompleted
        {
            get { return true; }
        }

        public event EventHandler LoadCompleted;
        public event EventHandler Saved;
        protected virtual void OnLoadCompleted()
        {
            if (LoadCompleted != null)
                LoadCompleted(this, EventArgs.Empty);
        }

        public void SetParameters(string parameters)
        {
            try
            {
                if (parameters == "")
                    Khoa = null;
                else
                    Khoa = Int32.Parse(parameters);
            }
            catch
            {
                Khoa = null;
            }
        }

        public string Title
        {
            get { return "BangKeBanRa"; }
        }

       
        #endregion

        #region Load Methods
        private System.Nullable<int> Khoa = null;
        private int Thang ;
        private int Nam;

        public int countSave = 0;
        public event EventHandler OnClosedChildWindow;
        TH_SoChiTiet_ListViewModel th_SoChiTiet_ListViewModel;
        public event EventHandler TinhBangKeBanRaCompleteted;
        public event EventHandler SaveCompleteted;
        public IList<TH_SoChiTietInfo> listSoChiTiet;

        public THUE_BangKeBanRa_ChildWindow(int Khoa)          
        {
            this.Khoa = Khoa;

            LocalizationConverter converter = new LocalizationConverter();
            converter.LocalResourceManager = new ResourceManager("csla4Skeleton.UI.SL.NghiepVu.THUE.THUE_BangKeBanRa.Resources", Assembly.GetExecutingAssembly());
            this.Resources.Add("Localization", converter);

            InitializeComponent();
            ControlBehavior.ControlBehaviors.Navigation(this.THUE_BangKeBanRa_ChungTuInformation_GroupBox, controls);
        }

        public THUE_BangKeBanRa_ChildWindow()
        {
            LocalizationConverter converter = new LocalizationConverter();
            converter.LocalResourceManager = new ResourceManager("csla4Skeleton.UI.SL.NghiepVu.THUE.THUE_BangKeBanRa.Resources", Assembly.GetExecutingAssembly());
            this.Resources.Add("Localization", converter);
            
            InitializeComponent();  
            ControlBehavior.ControlBehaviors.Navigation(this.THUE_BangKeBanRa_ChungTuInformation_GroupBox, controls);
           
        }
        public THUE_BangKeBanRa_ChildWindow(string thang, string nam)
        {
            LocalizationConverter converter = new LocalizationConverter();
            converter.LocalResourceManager = new ResourceManager("csla4Skeleton.UI.SL.NghiepVu.THUE.THUE_BangKeBanRa.Resources", Assembly.GetExecutingAssembly());
            this.Resources.Add("Localization", converter);

            InitializeComponent();
            ControlBehavior.ControlBehaviors.Navigation(this.THUE_BangKeBanRa_ChungTuInformation_GroupBox, controls);

            this.Thang = int.Parse(thang);
            this.Nam = int.Parse(nam);
           
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
            {

                System.Windows.Data.CollectionViewSource THUE_BangKeBanRa_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["THUE_BangKeBanRa_ViewModelSource"];
                if (Khoa == null)
                {
                    THUE_BangKeBanRa_ViewModel THUE_BangKeBanRa_ViewModel = new THUE_BangKeBanRa_ViewModel();
                    THUE_BangKeBanRa_ViewModel.ChildList_AddedNew += new THUE_BangKeBanRa_ViewModel.ChildList_AddedNew_EventHandler(THUE_BangKeBanRa_ViewModel_ChildList_AddedNew);              
                    THUE_BangKeBanRa_ViewModel.SoChiTietIdChanged += new THUE_BangKeBanRa_ViewModel.SoChiTietIdChanged_EventHandler(THUE_BangKeBanRa_SoChiTietIdChanged);                    
                    THUE_BangKeBanRa_ViewModel.LoadCompleted += new EventHandler(THUE_BangKeBanRa_ViewModel_LoadCompleted);
                    THUE_BangKeBanRa_ViewModel.Saved += new EventHandler(OnSaveCompleted);

                    THUE_BangKeBanRa_ViewModel.CountChanged += new EventHandler(OnCountChanged);  
                    THUE_BangKeBanRa_CollectionViewSource.Source = new List<object> { THUE_BangKeBanRa_ViewModel };
                    
                    
                }
                else
                {
                    THUE_BangKeBanRa_ViewModel THUE_BangKeBanRa_ViewModel = new THUE_BangKeBanRa_ViewModel((int)Khoa);
                    THUE_BangKeBanRa_ViewModel.ChildList_AddedNew += new THUE_BangKeBanRa_ViewModel.ChildList_AddedNew_EventHandler(THUE_BangKeBanRa_ViewModel_ChildList_AddedNew);
                    THUE_BangKeBanRa_ViewModel.SoChiTietIdChanged += new THUE_BangKeBanRa_ViewModel.SoChiTietIdChanged_EventHandler(THUE_BangKeBanRa_SoChiTietIdChanged);
                    THUE_BangKeBanRa_ViewModel.Saved += new EventHandler(OnSaveCompleted);
                    THUE_BangKeBanRa_CollectionViewSource.Source = new List<object> { THUE_BangKeBanRa_ViewModel };

                    System.Windows.Data.CollectionViewSource TH_SoChiTiet_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["TH_SoChiTiet_ListViewModelSource"];
                    th_SoChiTiet_ListViewModel = new TH_SoChiTiet_ListViewModel(this.Thang, this.Nam,"BangKeBanRa");
                    TH_SoChiTiet_CollectionViewSource.Source = new List<object> { th_SoChiTiet_ListViewModel };
                   
                    
                }

                this.THUE_BangKeBanRa_BangKeBanRaChiTietGridView.KeyboardCommandProvider = new ControlBehavior.GridViewKeyboardCommandProvider(this.THUE_BangKeBanRa_BangKeBanRaChiTietGridView);
                
                ((ControlBehavior.GridViewKeyboardCommandProvider)this.THUE_BangKeBanRa_BangKeBanRaChiTietGridView.KeyboardCommandProvider).ReachLastColumn += new ControlBehavior.GridViewKeyboardCommandProvider.ReachLastColumn_EventHandler(OnReachLastColumn);

                ((ControlBehavior.GridViewKeyboardCommandProvider)this.THUE_BangKeBanRa_BangKeBanRaChiTietGridView.KeyboardCommandProvider).TabKeyPress += new EventHandler(OnTabKeyPress);

            }
        }

        #endregion
       

        #region Event Handle
        private void LayoutRoot_KeyUp(object sender, KeyEventArgs e)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control)
            {
                THUE_BangKeBanRa_ViewModel vm = GetViewModel();
                if (e.Key == Key.S)
                {
                    if (vm.CanSave)
                    {
                        vm.Save(sender, new Csla.Xaml.ExecuteEventArgs());
                    }
                }
                else if (e.Key == Key.F6)
                {
                    AddItems();
                }
                else if (e.Key == Key.D1)
                {
                    this.THUE_BangKeBanRa_BangKeBanRaChiTietTab.IsSelected = true;
                }
               
               
                
            }
            e.Handled = true;
        }

        void AddItemButton_Click(object sender, RoutedEventArgs e)
        {

            AddItems();
        }

        void DeleteItemButton_Click(object sender, RoutedEventArgs e)
        {
            DeleteItems();
          
        }

        public void AddItems()
        {
            if (this.THUE_BangKeBanRa_BangKeBanRaChiTietTab.IsSelected)
            {
                AddBangKeBanRaDetailsItem();
            }
        }
        private RadGridView GetActiveGridView()
        {
            if (this.THUE_BangKeBanRa_BangKeBanRaChiTietTab.IsSelected)
            {
                return THUE_BangKeBanRa_BangKeBanRaChiTietGridView;
            }
           
            return null;
        }

        void DeleteItems()
        {
           if (this.THUE_BangKeBanRa_BangKeBanRaChiTietTab.IsSelected)
            {
                THUE_BangKeBanRa_ChiTietChild ChiTietChild = (THUE_BangKeBanRa_ChiTietChild)(this.THUE_BangKeBanRa_BangKeBanRaChiTietGridView.SelectedItem);
                IList<THUE_BangKeBanRa_ChiTietChild> list = GetViewModel().Model.THUE_BangKeBanRa_ChiTiets;
                int index = list.IndexOf(ChiTietChild);
                

                DeleteBangKeBanRaDeTailsItem(index);
            }
           
            
        }
           
        void GridView_AddingNewDataItem(object sender, GridViewAddingNewEventArgs e)
        {
            var grid = e.OwnerGridViewItemsControl;
            if (grid.Items.Count > 0)
            {
                GridViewUtil.FocusRow((RadGridView)grid, grid.Items.Count - 1);
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    grid.CurrentCellInfo = new GridViewCellInfo(grid.Items[grid.Items.Count - 1], grid.Columns[0]);
                    grid.Focus();
                    grid.BeginEdit();
                }));
            }
        }
              
        private void SaveAndNewButton_Click(object sender, RoutedEventArgs e)
        {
           THUE_BangKeBanRa_ViewModel vm = GetViewModel();
            vm.SaveAndNew();
        }

        private void DatePicker_KeyUp(object sender, KeyEventArgs e)
        {
            List<Control> availableControl = new List<Control>();
            foreach (Control item in controls)
            {
                if (item.Visibility == System.Windows.Visibility.Visible)
                {
                    availableControl.Add(item);
                }
            }
            Control[] list = availableControl.ToArray();
            if (sender.GetHashCode() == list[availableControl.Count - 1].GetHashCode())
            {
                if (e.Key == Key.Enter)
                {
                    this.AddBangKeBanRaDetailsItem();
                }
            }
            else
            {
                ControlBehavior.DatePickerBehaviors.DatePicker_KeyUp(sender, e, controls);
            }
        }

        private void ComboBox_KeyUp(object sender, KeyEventArgs e)
        {
            List<Control> availableControl = new List<Control>();
            foreach (Control item in controls)
            {
                if (item.Visibility == System.Windows.Visibility.Visible)
                {
                    availableControl.Add(item);
                }
            }
            Control[] list = availableControl.ToArray();
            if (sender.GetHashCode() == list[availableControl.Count - 1].GetHashCode())
            {
                if (e.Key == Key.Enter)
                {
                    this.AddBangKeBanRaDetailsItem();
                }
            }
            else
            {
                ControlBehavior.ComboBoxBehaviors.ComboBox_KeyUp(sender, e, controls);
            }
        }

        private void Control_KeyUp(object sender, KeyEventArgs e)
        {
            List<Control> availableControl = new List<Control>();
            foreach (Control item in controls)
            {
                if (item.Visibility == System.Windows.Visibility.Visible)
                {
                    availableControl.Add(item);
                }
            }
            Control[] list = availableControl.ToArray();
            if (sender.GetHashCode() == list[availableControl.Count - 1].GetHashCode())
            {
                if (e.Key == Key.Enter)
                {
                    this.AddBangKeBanRaDetailsItem();
                }
            }
            else
            {
                ControlBehavior.ControlBehaviors.Control_KeyUp(sender, e, controls);
            }
        }


        private void BookedItemButton_Click(object sender, RoutedEventArgs e)
        {
            GetViewModel().GhiSo();
        }

        private void DeleteBookedItemButton_Click(object sender, RoutedEventArgs e)
        {
            GetViewModel().BoGhi();
        }

        void OnTabKeyPress(object sender, EventArgs e)
        {
            this.tabControl.SelectedItem = tabControl.Items[0];
            this.AddBangKeBanRaDetailsItem();
        }

        void OnReachLastColumn(object sender, ReachLastColumnArgs e)
        {

            List<TabItem> AvailableTabItem = new List<TabItem>();
            int indexCurrentTab = 0;
            foreach (TabItem item in this.tabControl.Items)
            {
                if (item.Visibility == System.Windows.Visibility.Visible)
                {
                    AvailableTabItem.Add(item);
                    if (item.GetHashCode() == tabControl.SelectedItem.GetHashCode())
                    {
                        indexCurrentTab = AvailableTabItem.IndexOf(item);
                    }

                }
            }


            TabItem[] list = AvailableTabItem.ToArray();
            if (indexCurrentTab == (AvailableTabItem.Count - 1))
            {
                this.tabControl.SelectedItem = list[0];
                FocusAfterChangeTab(this.THUE_BangKeBanRa_BangKeBanRaChiTietGridView, e.Index);

            }
            

        }

        private void FocusAfterChangeTab(GridViewDataControl grid, int index)
        {
             
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    grid.CurrentCellInfo = new GridViewCellInfo(grid.Items[index], grid.Columns[0]);
                    grid.Focus();
                    grid.BeginEdit();
                }));
           
        }
        
        
       
        #endregion

        #region View Model Related Methods
        public THUE_BangKeBanRa_ViewModel GetViewModel()
        {
            System.Windows.Data.CollectionViewSource THUE_BangKeBanRa_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["THUE_BangKeBanRa_ViewModelSource"];
            return ((List<object>)THUE_BangKeBanRa_CollectionViewSource.Source)[0] as THUE_BangKeBanRa_ViewModel;
        }



        void THUE_BangKeBanRa_SoChiTietIdChanged(object sender, SoChiTietIdChangedEventArgs e)
        {
           
            /*THUE_BangKeBanRa_ChiTietChild ChiTietChild =  GetViewModel().Model.THUE_BangKeBanRa_ChiTiets[e.Index];

            System.Windows.Data.CollectionViewSource TSCD_KeKhai_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["TSCD_KeKhai_ListViewModelSource"];
            TSCD_KeKhai_ListViewModel tscd_KeKhai_ListViewModel = ((List<object>)TSCD_KeKhai_CollectionViewSource.Source)[0] as TSCD_KeKhai_ListViewModel;
            System.Collections.Generic.IList<TSCD_KeKhaiInfo> list = tscd_KeKhai_ListViewModel.Model.getListOfInfo();


            foreach (TSCD_KeKhaiInfo item in list)
            {
                if (item.Khoa == e.TSCDId)
                {
                    ChiTietChild.DienGiai = item.Ten;
                    
                    break;
                }
            }
             * */
          

     
        }
       
        private void THUE_BangKeBanRa_ViewModel_LoadCompleted(object sender, EventArgs e)
        {
            System.Windows.Data.CollectionViewSource TH_SoChiTiet_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["TH_SoChiTiet_ListViewModelSource"];
            th_SoChiTiet_ListViewModel = new TH_SoChiTiet_ListViewModel(this.Thang, this.Nam,"BangKeBanRa");
            th_SoChiTiet_ListViewModel.LoadCompleted += new EventHandler(OnTH_SoChiTietAndBangKeBanRaLoadCompleteted);
            TH_SoChiTiet_CollectionViewSource.Source = new List<object> { th_SoChiTiet_ListViewModel };
        }

      
        private void OnTH_SoChiTietAndBangKeBanRaLoadCompleteted(object sender, EventArgs e)
        {
            this.GetViewModel().Model.Thang = this.Thang;
            this.GetViewModel().Model.Nam = this.Nam;

            System.Windows.Data.CollectionViewSource TH_SoChiTiet_CollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["TH_SoChiTiet_ListViewModelSource"];
            TH_SoChiTiet_ListViewModel th_SoChiTiet_ListViewModel = ((List<object>)TH_SoChiTiet_CollectionViewSource.Source)[0] as TH_SoChiTiet_ListViewModel;
            listSoChiTiet = th_SoChiTiet_ListViewModel.Model.getListOfInfo();
            foreach(TH_SoChiTietInfo item in listSoChiTiet)
            {
                this.AddBangKeBanRaDetailsItem();
            }
            
        }

        private void OnCountChanged(object sender, EventArgs e)
        {
            TH_SoChiTietInfo[] SoChiTietArray  = new TH_SoChiTietInfo[listSoChiTiet.Count];
            listSoChiTiet.CopyTo(SoChiTietArray,0);

            if (listSoChiTiet.Count == this.GetViewModel().Model.THUE_BangKeBanRa_ChiTiets.Count)
            {
                int index = 0;
                foreach (THUE_BangKeBanRa_ChiTietChild item in this.GetViewModel().Model.THUE_BangKeBanRa_ChiTiets)
                {
                    item.KHHoaDon = SoChiTietArray[index].KHHoaDon;
                    item.SoHD = SoChiTietArray[index].SoHD;
                    item.NgayHD = SoChiTietArray[index].NgayHD;
                    item.LoaiHoaDon = SoChiTietArray[index].LoaiHD;
                    item.TenNhaCungCap = SoChiTietArray[index].TenNhaCungCap;
                    item.MaSoThue = SoChiTietArray[index].MST;
                    item.TongTienHang = SoChiTietArray[index].TongTienHang  *  SoChiTietArray[index].TyGia;
                    item.DienGiai = SoChiTietArray[index].DienGiai;
                    item.ThueSuat = SoChiTietArray[index].ThueSuat;
                    item.TienThue = SoChiTietArray[index].SoTien;
                    item.SoChiTietId = SoChiTietArray[index].Khoa;
                    index++;
                   
                }
                GetViewModel().Model.TinhTongTienThue();
                this.GetViewModel().Save(this, new Csla.Xaml.ExecuteEventArgs());
               

            }
        }
        
        private void OnSaveCompleted(object sender, EventArgs e)
        {
            
            if (TinhBangKeBanRaCompleteted != null)
            {
                TinhBangKeBanRaCompleteted(this, new EventArgs());
                
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            if (OnClosedChildWindow != null)
            {
                OnClosedChildWindow(this, new EventArgs());
            }
            base.OnClosed(e);
            
        }
        private void AddBangKeBanRaDetailsItem()
        {
            GetViewModel().AddTHUE_BangKeBanRa_ChiTietItem();
        }
        private void DeleteBangKeBanRaDeTailsItem(int Index)
        {
            GetViewModel().DeleteTHUE_BangKeBanRa_ChiTietItem( Index);
        }

        void THUE_BangKeBanRa_ViewModel_ChildList_AddedNew(object sender, ChildListAddedNewArgs e)
        {
            if (e.ChildListName == "THUE_BangKeBanRa_ChiTiets")
            {
                this.THUE_BangKeBanRa_BangKeBanRaChiTietGridView.OnAddingNewDataItem(new GridViewAddingNewEventArgs(GetActiveGridView()));
            }
        }

       
        #endregion
        
    }
}
